﻿using CuoDing.Core;
using CuoDing.Core.BLL;
using CuoDing.Core.Common;
using CuoDing.Core.Model.Enum;
using CuoDing.Core.Model.Model;
using CuoDing.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DX.StdTrainning.WebApi.Controllers
{
    /// <summary>
    /// 登录管理【无权限】
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [AllowAnonymous]

    public class LoginController : ControllerBase
    {
        private readonly IUser _user;
        private readonly ISystemUserBLL _systemUserBLL;

        public LoginController(IUser user, ISystemUserBLL systemUserBLL)
        {
            _user = user;
            _systemUserBLL = systemUserBLL;
        }

        /// <summary>
        /// 登录获取token
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpPost]
        [NoEncryptActionAttribute]
        public async Task<dynamic> GetToken([FromBody]SystemUser param)
        {
            string jwtStr = string.Empty;
            var obj = await _systemUserBLL.LoginToken(param);
            if (obj != null&& obj.code==DXCode.Success)
            {
                var user = obj.data as SystemUser;
                TokenModelJwt tokenModel = new TokenModelJwt { UserId = user.Id.ToString(), CreateDept ="测试部门" };
                jwtStr = JwtHelper.IssueJwt(tokenModel);
                obj.data = jwtStr;
            }

            return obj;
        }


        /// <summary>
        /// 刷新Token（以旧换新）
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<dynamic> RefreshToken(string token)
        {
            DXResult dXResult = new DXResult { code = DXCode.Success ,msg="刷新成功"};
            string jwtStr = string.Empty;
            var userInfo = JwtHelper.SerializeJwt(token);
            if (userInfo == null)
            {
                return new DXResult { code = DXCode.Failure, msg = "无效token" };
            }
            var refreshExpires = userInfo?.RefreshExpires;
            if (!refreshExpires.IsNotEmptyOrNull())
            {
                return new DXResult { code = DXCode.Failure, msg = "无效刷新时间" };
            }

            if (refreshExpires.ObjToLong() <= DateTime.Now.ObjToTimestamp())
            {
                return new DXResult { code = DXCode.Failure, msg = "登录信息已过期" };
            }

            var userId = userInfo?.UserId;
            if (!userId.IsNotEmptyOrNull())
            {
                return new DXResult { code = DXCode.Failure, msg = "用户信息为空" };
            }
            var dXResultUser = await _systemUserBLL.TokenGetById(userId.ObjToLong());
            if (dXResultUser.code != DXCode.Success)
            {
                return new DXResult { code = DXCode.Failure, msg = "获取用户信息失败" };
            }
            var userObj = dXResultUser.data as SystemUser;
            TokenModelJwt tokenModel = new TokenModelJwt { UserId = userObj.Id.ToString(), CreateDept = "测试刷新部门" };
            jwtStr = JwtHelper.IssueJwt(tokenModel);
            dXResult.data = jwtStr;
            return dXResult;
        }

        /// <summary>
        /// 测试获取登录用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public  dynamic GetUserTest()
        {
            DXResult dXResult = new DXResult { code = DXCode.Success };
            var userObj = new 
            {
                id=_user.Id,
                dept=_user.CreateDept
            };
            dXResult.data = userObj;
            return dXResult;
        }

    }
}
